package com.dashan.servlets;

import static com.dashan.Constants.POSITION_ACC;
import static com.dashan.Constants.POSITION_DESC;
import static com.dashan.Constants.POSITION_LAT;
import static com.dashan.Constants.POSITION_LNG;
import static com.dashan.Constants.SUCCESS;
import static com.dashan.Constants.USERNAME;
import static com.dashan.servlets.Parameter.Option.Optional;
import static com.dashan.servlets.Parameter.Option.Required;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.TreeMap;

import javax.jdo.JDOObjectNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dashan.backend.datastore.DsPosition;
import com.dashan.backend.datastore.DsUser;
import com.dashan.backend.datastore.UserDao;

@SuppressWarnings("serial")
public class PostPositionServlet extends DashanPrivateServlet {

    @Override
    public ArrayList<Parameter> getParameterList() {
        ArrayList<Parameter> res = super.getParameterList();
        res.add(new Parameter(POSITION_ACC, Required, Double.class));
        res.add(new Parameter(POSITION_LAT, Required, Double.class));
        res.add(new Parameter(POSITION_LNG, Required, Double.class));
        res.add(new Parameter(POSITION_DESC, Optional, String.class));
        return res;
    }

    @Override
    public String getUrlPattern() {
        return "/postposition";
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        TreeMap<String, Parameter> params = loadParamters(req);
        UserDao dao = new UserDao();
        try {
            DsUser user = dao.getUser(params.get(USERNAME).stringValue());
            DsPosition position = new DsPosition(
                    params.get(USERNAME).stringValue(),
                            params.get(POSITION_LNG).doubleValue(),
                                    params.get(POSITION_LAT).doubleValue(),
                    params.get(POSITION_ACC).doubleValue(),
                    new Date());
            if (params.get(POSITION_DESC).hasValue()) {
                position.setDescription(params.get(POSITION_DESC).stringValue());
            }
            user.setPosition(position);
        } catch (JDOObjectNotFoundException e) {
            throw new ServletException("Cannot post position: " + e.getMessage());
        } finally {
            dao.commit();
        }

        resp.getWriter().println(SUCCESS);
    }
}
